import router from './router'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from '@/utils/get-page-title'
import { getCookies } from './utils/auth'
import { Notification } from 'element-ui'
import store from './store'
NProgress.configure({ showSpinner: false }) // NProgress Configuration

router.beforeEach((to, from, next) => {
  const hasToken = getCookies('admin-Token')
  const hasUserInfo = getCookies('userInfo')
  // set page title
  document.title = getPageTitle(to.meta.title)
  NProgress.start()
  if (to.path === '/login' && !hasToken) {
    next()
    return NProgress.done()
  }
  if (!hasToken || !hasUserInfo) {
    store.commit('user/removeToken')
    next('/login')
    Notification({
      title: '警告',
      message: '请先登录',
      type: 'warning',
      position: 'top-left'
    })
    return NProgress.done()
  }
  // start progress bar
  hasToken && to.path === '/login' ? next('/') : next()
  NProgress.done()
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
